#include "dialog.h"
#include "ui_dialog.h"
#include "QDebug"
#include <QFile>
#include <QTextStream>
#include <QDateTime>
#include <codecvt>
#include <locale>
#include <string>
#include <QMessageBox>

#define NOT_START 0
#define COUNTING 1
#define PAUSE 2
#define PUSHTIMES 25

#define MULTY 0

unsigned int time_s = 5;
unsigned int count_all = 2;
unsigned int all_time_s = time_s;
QString cal_type = "--";


Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);

    hr = CoInitialize(nullptr);
    if (FAILED(hr)) {
        qDebug() << "CoInitialize failed!";
    } else {
        hr = CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
        if (FAILED(hr)) {
            qDebug() << "Failed to create ISpVoice!";
            CoUninitialize();
        }
    }

    player = new QMediaPlayer;
    timer = new QTimer();
    connect(timer, SIGNAL(timeout()), this, SLOT(onTimeout()));

    start_flag = NOT_START;
    count = 0;
    noupdate_time = 0;
    ui->label_err->setVisible(false);
    ui->pushButton_start->setText("开始");
    ui->label_count->setText(QString::number(count));
    while (!update()) ;
    ui->progressBar->setValue(0);
    ui->progressBar_time->setValue(0);
    previousStyleSheet = ui->progressBar->styleSheet();
    ui->progressBar->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: green; }");
    ui->progressBar_time->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: green; }");
    ui->label->setText(QString::number(time_s/60) + ":" + QString::number(time_s%60));
    ui->label_all->setText(QString::number(count_all));
    timer->start(200); // 设置为1000毫秒，即1秒
    ui->pushButton_start->setStyleSheet("QPushButton { background-color: white; color: black; }");
    las_time_s = time_s;

    QPixmap cursorPixmap("../Calculator/img/sssss.png"); // 替换为你的图片路径
    QCursor customCursor(cursorPixmap);
    setCursor(customCursor);
}

Dialog::~Dialog()
{
    if (pVoice) {
        pVoice->Release();
    }

    CoUninitialize();
    delete ui;
}

bool Dialog::sub100()
{
    cal_type = "sub100";
    //100减100以内的数
    int randomNumber1 = QRandomGenerator::global()->bounded((unsigned int)20,(unsigned int)100) + 1;
    int randomNumber2 = QRandomGenerator::global()->bounded((unsigned int)10,(unsigned int)randomNumber1) + 1;

    ui->label_add->setText("-");
    ui->lineEdit->clear();

    if((randomNumber1 > randomNumber2) && (randomNumber1%10 < randomNumber2%10)){
        ui->label_1->setText(QString::number(randomNumber1));
        ui->label_2->setText(QString::number(randomNumber2));
        return true;
    } else {
        return false;
    }
}

bool Dialog::sub10()
{
    cal_type = "sub10";
    int randomNumber1 = QRandomGenerator::global()->bounded((unsigned int)0,(unsigned int)10) + 1;
    int randomNumber2 = QRandomGenerator::global()->bounded((unsigned int)0,(unsigned int)randomNumber1) + 1;

    ui->label_add->setText("-");
    ui->lineEdit->clear();

    if((randomNumber1 > randomNumber2) && (randomNumber1%10 < randomNumber2%10)){
        ui->label_1->setText(QString::number(randomNumber1));
        ui->label_2->setText(QString::number(randomNumber2));
        return true;
    } else {
        return false;
    }
}



bool Dialog::update()
{
    if(MULTY){
        update();
        return true;
    }

//    return sub100();
    return sub10();
}

void Dialog::write_file()
{
    QDateTime currentTime = QDateTime::currentDateTime();
    QString timeString = currentTime.toString("yyyy-MM-dd HH:mm:ss");

    QString filePath = "../Calculator/log.txt";
    QFile file(filePath);
    if (!file.open(QIODevice::Append | QIODevice::Text))
            return ; // 无法打开文件

     QTextStream out(&file);
     QString lineToAppend = timeString + " " + cal_type + " " + QString::number(all_time_s) + "S " + ui->label_count->text() + "\n";
     out << lineToAppend;
     file.close();
}

void Dialog::play_file()
{
    int count = ui->label_count->text().toInt();
    if(count == 9){
        player->setMedia(QUrl::fromLocalFile("../Calculator/mp3/鼓掌2.mp3"));
    } else if(count == 19){
        player->setMedia(QUrl::fromLocalFile("../Calculator/mp3/鼓掌喝彩3.mp3"));
    } else if(count == 29){
        player->setMedia(QUrl::fromLocalFile("../Calculator/mp3/加油呐喊音效.mp3"));
    } else {
        if(((count - 4)%5) == 0){
            player->setMedia(QUrl::fromLocalFile("../Calculator/mp3/你真棒.mp3"));
        } else {
            player->setMedia(QUrl::fromLocalFile("../Calculator/mp3/great.mp3"));
        }
    }
    player->play();

}

void Dialog::TTS_play()
{
    std::wstring wstr = play_str.toStdWString();
    const wchar_t* lpcwstr = wstr.c_str();
    if (pVoice) {
        hr = pVoice->Speak(lpcwstr,SPF_ASYNC, nullptr);
        if (FAILED(hr)) {
            qDebug() << "Failed to speak!";
        }
    }
}


void Dialog::on_pushButton_start_clicked()
{
    if(start_flag == NOT_START){
        start_flag = COUNTING;
        ui->pushButton_start->setText("暂停");
        ui->pushButton_start->setStyleSheet("QPushButton { background-color: white; color: black; }");
    } else if(start_flag == COUNTING){
        start_flag = PAUSE;
        ui->pushButton_start->setText("继续");
        ui->pushButton_start->setStyleSheet("QPushButton { background-color: yellow; color: black; }");
    } else if(start_flag == PAUSE){
        start_flag = COUNTING;
        ui->pushButton_start->setText("暂停");
        ui->pushButton_start->setStyleSheet("QPushButton { background-color: white; color: black; }");
    }
}

void Dialog::onTimeout()
{
    if(ui->pushButton_start->text() == "暂停"){
        check(false);
        if(time_s > 0){
            if(las_time_s != QTime::currentTime().second()){
                time_s--;
                noupdate_time++;
                if(noupdate_time == PUSHTIMES){
                    player->setMedia(QUrl::fromLocalFile("../Calculator/mp3/继续努力.mp3"));
                    player->play();
                } else if(noupdate_time == (PUSHTIMES * 2)){
                    noupdate_time = 0;
                    player->setMedia(QUrl::fromLocalFile("../Calculator/mp3/喊老大加油.mp3"));
                    player->play();
                }
                if(time_s == 0){
                    ui->pushButton_ok->setEnabled(false);
                    write_file();
                    timer->stop();
                    play_str = "你需要完成" + QString::number(count_all) + "道题，实际完成了" + ui->label_count->text() + "道题计算，继续加油！加油！";
                    TTS_play();
                    QMessageBox::information(this, "计算结束", play_str);
                }

                ui->label->setText(QString::number(time_s/60) + ":" + QString::number(time_s%60));
                ui->progressBar->setValue(ui->label_count->text().toUInt() * 100/count_all);
                ui->progressBar_time->setValue(100 - time_s * 100/all_time_s);

                if(ui->progressBar_time->value() > 10 && ui->progressBar_time->value() < 90){
                    if((ui->progressBar_time->value() - ui->progressBar->value()) >= 20){
                        ui->progressBar->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: red; }");
                        ui->progressBar_time->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: red; }");
                    } else if((ui->progressBar_time->value() - ui->progressBar->value()) >= 10){
                        ui->progressBar->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: yellow; }");
                        ui->progressBar_time->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: yellow; }");
                    } else {
                        ui->progressBar->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: green; }");
                        ui->progressBar_time->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: green; }");
                    }
                } else if(ui->progressBar_time->value() > 90){
                    if(ui->progressBar->value() <= 90){
                        ui->progressBar->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: red; }");
                        ui->progressBar_time->setStyleSheet(previousStyleSheet + "QProgressBar::chunk { background-color: red; }");
                    }
                }

                err_show++;
                if(err_show == 2){
                    ui->label_err->setVisible(false);
                    err_show = 0;
                }
            }
        }
    }

    las_time_s = QTime::currentTime().second();
}

void Dialog::on_pushButton_ok_clicked()
{
    if(start_flag == PAUSE){
            start_flag = COUNTING;
            ui->pushButton_start->setText("暂停");
            ui->pushButton_start->setStyleSheet("QPushButton { background-color: white; color: black; }");
    }

    if(ui->lineEdit->text().size() == 0){
        return;
    }

    if(start_flag == NOT_START){
        start_flag = COUNTING;
        ui->pushButton_start->setText("暂停");
        ui->pushButton_start->setStyleSheet("QPushButton { background-color: white; color: black; }");

    }

    if(ui->pushButton_start->text() == "暂停"){
        if(time_s > 0){
            check(true);
        }
    }
}


void Dialog::check(bool if_err)
{
    bool temp = false;
    int add1 = ui->label_1->text().toInt();
    int add2 = ui->label_2->text().toInt();
    int input_end = ui->lineEdit->text().toInt();

    if((ui->label_add->text() == "+") && (input_end == (add1 + add2))){
        temp = true;
    } else if((ui->label_add->text() == "-") && (input_end == (add1 - add2))){
        temp = true;
    } else if((ui->label_add->text() == "*") && (input_end == (add1 * add2))){
        temp = true;
    } else if((ui->label_add->text() == "÷") && (input_end == (add1/add2))){
        temp = true;
    } else {
        if(if_err){
            ui->label_err->setVisible(true);
            ui->lineEdit->clear();
            play_str = "再想想！";
            TTS_play();
        }
        return;
    }

    noupdate_time = 0;
    play_file();
    while (!update()) ;
    ui->label_count->setText(QString::number(ui->label_count->text().toInt() + 1));
}


void Dialog::on_lineEdit_textChanged(const QString &arg1)
{
    if(ui->pushButton_start->text() == "开始"){
        if(start_flag == PAUSE){
                start_flag = COUNTING;
                ui->pushButton_start->setText("暂停");
                ui->pushButton_start->setStyleSheet("QPushButton { background-color: white; color: black; }");
        }

        if(ui->lineEdit->text().size() == 0){
            return;
        }

        if(start_flag == NOT_START){
            start_flag = COUNTING;
            ui->pushButton_start->setText("暂停");
            ui->pushButton_start->setStyleSheet("QPushButton { background-color: white; color: black; }");

        }
    }
}
